using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading; 
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using Microsoft.Advertising.Mobile.Xna;
using System.Diagnostics;

namespace MeteorShower
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class GameView : Microsoft.Xna.Framework.DrawableGameComponent
    {
        bool firstTime = true;
        bool shipdraw = true;
        bool just_hit = false;
        int number_of_asteroids = 10;
        Ship ship1;
        SpriteBatch spriteBatch;
        float rotationangle;
        bool bulletbuttonreleased = true;
        Texture2D gameoverscreen, scorebox, bulletart, bulletbutton, bar1, bar2, bar3, bar4, bar5, sqr, meteor, green, shipfire2, shipfire1, MenuText, play, quit, line, ingametitle, menu, pause, healthbar, stickoutline, circle, newshipnofire;
        Vector2 bulletbuttonposition, origin2, titlescreen, play_text, quit_text, line_spot, ingametitlelocation, menu_text, pause_text, healthbar_location, stick_outline, circle_location;
        SpriteFont segoe14;
        string TEXT = "Canis";
        int s_y = 480;
        int s_x = 840;
        int s_distance = 0;
        int score = 0;
        int high_score = 0;
        int lives = 5;
        int bullets = 5;
        int bullets_in_inventory;
        double angle = 0;
        static AdGameComponent adGameComponent;
        static DrawableAd bannerAd;
        Meteor[] meteornumber = new Meteor[10];
        bullet[] bulletnumber = new bullet[5];
        const string AppID = "18bf1f7a-d1e0-415f-841d-7167c8bc88e5";
        const string AdUnitID = "77535";
        int touchx = 0;
        int touchy = 0;
        int current_distance = 0;
        double new_touch_x = 0;
        double new_touch_y = 0;
        bool shipmoving = false;
        bool draw_green_menu = false;
      
       
        public GameView(Game game)
            : base(game)
        {
            // TODO: Construct any child components here
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {

            Debug.WriteLine("GAME VIEW INITIALIZE");
            // TODO: Add your initialization code here

            base.Initialize();
        }

        protected override void LoadContent()
        {
            Debug.WriteLine("GAME VIEW LOAD CONTENT");
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // Create an adGameComponent for this game
            //AdGameComponent.Initialize(Game, AppID);
            //adGameComponent = AdGameComponent.Current;
            //Components.Add(adGameComponent);

            // Banner Ad Creation
            //bannerAd = adGameComponent.CreateAd(AdUnitID, new Rectangle(1, 1, 300, 50));
            //AdGameComponent.Current.Enabled = true;
            Viewport viewport = this.GraphicsDevice.Viewport;
          
            //Sprites
            meteor = Game.Content.Load<Texture2D>(Game1.getTheme().getAsteroid());
            shipfire2 = Game.Content.Load<Texture2D>(Game1.getTheme().getShipFire2());
            shipfire1 = Game.Content.Load<Texture2D>(Game1.getTheme().getShipFire1());
            newshipnofire = Game.Content.Load<Texture2D>(Game1.getTheme().getShipNoFire());
            bulletart = Game.Content.Load<Texture2D>(Game1.getTheme().getBullet());

            MenuText = Game.Content.Load<Texture2D>(Game1.getTheme().getTitleText());
            green = Game.Content.Load<Texture2D>("green");
            play = Game.Content.Load<Texture2D>(Game1.getTheme().getPlay());
            quit = Game.Content.Load<Texture2D>(Game1.getTheme().getQuit());
            line = Game.Content.Load<Texture2D>("line");
            menu = Game.Content.Load<Texture2D>(Game1.getTheme().getMenu());
            pause = Game.Content.Load<Texture2D>(Game1.getTheme().getPause());
            ingametitle = Game.Content.Load<Texture2D>(Game1.getTheme().getInGameTitle());
            sqr = Game.Content.Load<Texture2D>("square");
            healthbar = Game.Content.Load<Texture2D>("healthbar");
            stickoutline = Game.Content.Load<Texture2D>(Game1.getTheme().getCircleOutline());
            circle = Game.Content.Load<Texture2D>(Game1.getTheme().getCircle());

            bar1 = Game.Content.Load<Texture2D>("healthbar1");
            bar2 = Game.Content.Load<Texture2D>("healthbar2");
            bar3 = Game.Content.Load<Texture2D>("healthbar3");
            bar4 = Game.Content.Load<Texture2D>("healthbar4");
            bar5 = Game.Content.Load<Texture2D>("healthbar5");

            bulletbutton = Game.Content.Load<Texture2D>("bulletbutton");
            scorebox = Game.Content.Load<Texture2D>("scorebox");
            gameoverscreen = Game.Content.Load<Texture2D>(Game1.getTheme().getGameOverText());



            //FONTS
            segoe14 = Game.Content.Load<SpriteFont>("Segoe14");
            //Vector2 textSize = segoe14.MeasureString(TEXT);



            // thebullet = new bullet(); 
            //Sprite Locations
            //Vector2 ingametitlelocation = new Vector2(0, s_y / 16);

            origin2.X = meteor.Width / 2;
            origin2.Y = meteor.Height / 2;

            quit_text.X = 4 * s_x / 8;
            quit_text.Y = s_y / 2 + 50;

            menu_text.X = 6 * s_x / 16;
            menu_text.Y = 0;

            play_text.X = 3 * s_x / 8;
            play_text.Y = s_y / 2 + 50;

            healthbar_location.X = 7 * s_x / 16;
            healthbar_location.Y = 0;

            stick_outline.X = 0;
            stick_outline.Y = 3 * s_y / 6;

            circle_location.X = 0 + 50;
            circle_location.Y = 3 * s_y / 6 + 50;


            bulletbuttonposition.X = 14 * s_x / 16;
            bulletbuttonposition.Y = 6 * s_y / 8;
        }

        public void reloadContent()
        {
            this.LoadContent();
        }

        public void reset()
        {
            score = 0;
            //Defining the Ship Object
            ship1 = new Ship();

            //Creating the asteroids 
            for (int i = 0; i < number_of_asteroids; i++)
            {
                meteornumber[i] = new Meteor();
                Thread.Sleep(100);
            }

            for (int i = 0; i < bullets; i++)
            {
                bulletnumber[i] = new bullet();
            }
            firstTime = false;
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            if(Game1.getGameState().Equals("gameview")){
                //Handling back button being pressed
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    Game1.setGameState("mainmenuview");
                }
            //Recieving touch input 
            var mouseState = Mouse.GetState();
            TouchCollection touchCollection = TouchPanel.GetState();
            //bannerAd.Visible = true;
            score++;
            foreach (TouchLocation tl in touchCollection)
            {
                if ((tl.State == TouchLocationState.Pressed))
                {
                    if (tl.Position.X > bulletbuttonposition.X && tl.Position.X < bulletbuttonposition.X + 100)
                    {
                        if (tl.Position.Y > bulletbuttonposition.Y && tl.Position.Y < bulletbuttonposition.Y + 50)
                        {
                            if (bulletbuttonreleased == true)
                            {
                                for (int i = 0; i < bullets; i++)
                                {
                                    if (bulletnumber[i].ininventory() == true)
                                    {
                                        bulletnumber[i].shoot(ship1.getshipx(), ship1.getshipy());
                                        i = 100;
                                    }
                                }
                                bulletbuttonreleased = false;
                            }
                        }
                    }
                }
                if ((tl.State == TouchLocationState.Released))
                {
                    if (tl.Position.X > bulletbuttonposition.X && tl.Position.X < bulletbuttonposition.X + 25)
                    {
                        if (tl.Position.Y > bulletbuttonposition.Y && tl.Position.Y < bulletbuttonposition.Y + 50)
                        {
                            bulletbuttonreleased = true;
                        }
                    }
                }

            }





            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                touchx = mouseState.X;
                touchy = mouseState.Y;
                current_distance = ((touchx - 100) * (touchx - 100) + (touchy - (3 * s_y / 6 + 100)) * (touchy - (3 * s_y / 6 + 100)));
                double new_current_distance = System.Math.Sqrt(current_distance);

                //If touch is too high do nothing
                if (touchy < s_y / 8 || touchx > 13 * s_x / 16)
                {
                }

                //If touch is within the joystick
                else if (new_current_distance < 100)
                {
                    shipmoving = true;
                    circle_location.X = touchx - 50;
                    circle_location.Y = touchy - 50;
                    ship1.move(touchx, touchy);
                }


                //If touch is outside of the joystick but not in top bar
                else
                {
                    shipmoving = true;
                    new_touch_x = touchx - 100;
                    new_touch_y = -1 * touchy + 340;

                    angle = Math.Atan(new_touch_x / new_touch_y);


                    if (new_touch_y > 0)
                    {
                        circle_location.X = (float)(Math.Sin(angle) * 100 + 100 - 50);
                        circle_location.Y = (float)(Math.Cos(angle) * -100 + 340 - 50);
                    }
                    else
                    {
                        circle_location.X = (float)(Math.Sin(angle) * -100 + 100 - 50);
                        circle_location.Y = (float)(Math.Cos(angle) * 100 + 340 - 50);
                    }
                    touchx = (int)circle_location.X + 50;
                    touchy = (int)circle_location.Y + 50;
                    ship1.move(touchx, touchy);
                }



                //If touch is on MENU button
                if (mouseState.X > menu_text.X && mouseState.X < menu_text.X + 100)
                {
                    if (mouseState.Y > menu_text.Y && mouseState.Y < menu_text.Y + 50)
                    {
                        draw_green_menu = true;
                    }
                    else
                    {
                        draw_green_menu = false;
                    }
                }


            }

            // If button is released and Meu is selected 
            if (mouseState.LeftButton == ButtonState.Released)
            {
                if (mouseState.X > menu_text.X && mouseState.X < menu_text.X + 100)
                {
                    if (mouseState.Y > menu_text.Y && mouseState.Y < menu_text.Y + 50)
                    {
                        Game1.setGameState("mainmenuview");

                    }
                }
                draw_green_menu = false;
                shipmoving = false;
                circle_location.X = 50;
                circle_location.Y = 3 * s_y / 6 + 50;
            }

            //METEOR MOVEMENT
            //-------------------------------------------------------------------------------------
            for (int i = 0; i < number_of_asteroids; i++)
            {
                meteornumber[i].Move();
                meteornumber[i].CheckMeteor();

            }

            for (int i = 0; i < bullets; i++)
            {
                if (bulletnumber[i].isactive() == true)
                {
                    bulletnumber[i].move(s_x);
                }

            }

            //-------------------------------------------------------------------------------------

            //Assign Rectangle to ship


            Rectangle ship_rectangle = new Rectangle((int)ship1.getshipx(), (int)ship1.getshipy(), 50, 50);

            for (int i = 0; i < number_of_asteroids; i++)
            {

                Rectangle meteor_rectangle = new Rectangle((int)meteornumber[i].getmeteorx(), (int)meteornumber[i].getmeteory(), 50, 50);


                // Rectangle meteor_rectangle = new Rectangle((int)meteornumber[i].getmeteorx(), (int)meteornumber[i].getmeteory(), (int) (50*meteornumber[i].getmeteorsize2()), (int)(50 * meteornumber[i].getmeteorsize2())); 
                //Rectangle meteor_rectangle = new Rectangle( (int)(meteornumber[i].getmeteorx() - 25 * meteornumber[i].getmeteorsize2()),
                //  (int)(meteornumber[i].getmeteory() - 25 * meteornumber[i].getmeteorsize2()),
                //(int)(25 * meteornumber[i].getmeteorsize2()),
                //(int)(25 * meteornumber[i].getmeteorsize2())); 
                if (ship_rectangle.Intersects(meteor_rectangle))
                {
                    meteornumber[i].Respawn();
                    just_hit = true;
                    lives--;

                    if (lives < 1)
                    {
                        if (score > high_score)
                            high_score = score;
                        Game1.setScore(score);
                        Game1.setGameState("gameoverview");
                        lives = 5;

                    }
                }
                for (int j = 0; j < bullets; j++)
                {
                    if (bulletnumber[j].isactive())
                    {
                        Rectangle bullet_rectangle = new Rectangle((int)bulletnumber[j].getbulletposition().X, (int)bulletnumber[j].getbulletposition().Y, 25, 50);
                        if (bullet_rectangle.Intersects(meteor_rectangle))
                        {
                            meteornumber[i].Respawn();
                            bulletnumber[j].collide();

                        }
                    }
                }

                //rotation
                rotationangle += .1f;
                base.Update(gameTime);
            }
            }
        }
        public override void Draw(GameTime gameTime)
        {
          if(Game1.getGameState().Equals("gameview")){  
            spriteBatch.Begin();
            if (just_hit == true)
            {
                GraphicsDevice.Clear(Color.Red);
                just_hit = false;
            }

            else
            {
                //background
                GraphicsDevice.Clear(Color.Black);
            }


     

                for (int i = 0; i < number_of_asteroids; i++)
                {
                    spriteBatch.Draw(meteor, meteornumber[i].getmeteorposition(), null, Color.White, rotationangle, new Vector2(meteor.Width / 2, meteor.Height / 2), meteornumber[i].getmeteorsize(), SpriteEffects.None, 0f);

                }

                if (draw_green_menu == true)
                {
                    spriteBatch.Draw(green, menu_text, Color.White);
                }
                spriteBatch.Draw(line, new Vector2(0, s_y / 8), Color.White);
                //spriteBatch.Draw(ingametitle, ingametitlelocation, Color.White);
                spriteBatch.Draw(menu, menu_text, Color.White);
                spriteBatch.Draw(scorebox, new Vector2(13 * s_x / 16, 0), Color.White);
                spriteBatch.Draw(pause, new Vector2(8 * s_x / 16, 0), Color.White);
                spriteBatch.Draw(bulletbutton, bulletbuttonposition, Color.White);

                for (int i = 0; i < bullets; i++)
                {
                    if (bulletnumber[i].ininventory() == true)
                    {
                        bullets_in_inventory++;
                    }
                    else if (bulletnumber[i].isactive() == true)
                    {
                        spriteBatch.Draw(bulletart, bulletnumber[i].getbulletposition(), null, Color.White, 0f, new Vector2(bulletart.Width / 2, bulletart.Height / 2), .5f, SpriteEffects.None, 0f);
                    }
                }
                spriteBatch.DrawString(segoe14, bullets_in_inventory.ToString(), new Vector2(29 * s_x / 32, 6 * s_y / 8), Color.White);
                bullets_in_inventory = 0;
                if (lives >= 0)
                {
                    spriteBatch.Draw(bar1, healthbar_location, Color.White);
                    healthbar_location.X += 25;
                    if (lives >= 2)
                    {
                        spriteBatch.Draw(bar2, healthbar_location, Color.White);
                        healthbar_location.X += 25;
                        if (lives >= 3)
                        {
                            spriteBatch.Draw(bar3, healthbar_location, Color.White);
                            healthbar_location.X += 25;
                            if (lives >= 4)
                            {
                                spriteBatch.Draw(bar4, healthbar_location, Color.White);
                                healthbar_location.X += 25;

                                if (lives == 5)
                                {
                                    spriteBatch.Draw(bar5, healthbar_location, Color.White);

                                }
                            }
                        }
                    }
                }

                healthbar_location.X = 21 * s_x / 32; ;
                spriteBatch.Draw(stickoutline, stick_outline, Color.White);
                spriteBatch.DrawString(segoe14, score.ToString(), new Vector2(53 * s_x / 64, 25), Color.White);

                if (s_distance < 50)
                {
                    spriteBatch.Draw(circle, circle_location, Color.White);
                }


                if (!shipmoving)
                {
                    spriteBatch.Draw(newshipnofire, ship1.getshipposition(), null, Color.White, 0f, new Vector2(newshipnofire.Width / 2, newshipnofire.Height / 2), .1f, SpriteEffects.None, 0f);
                }
                else
                {


                    if (shipdraw == true)
                    {
                        spriteBatch.Draw(shipfire1, ship1.getshipposition(), null, Color.White, 0f, new Vector2(newshipnofire.Width / 2, newshipnofire.Height / 2), .1f, SpriteEffects.None, 0f);
                        shipdraw = false;
                    }

                    else if (shipdraw == false)
                    {
                        spriteBatch.Draw(shipfire2, ship1.getshipposition(), null, Color.White, 0f, new Vector2(newshipnofire.Width / 2, newshipnofire.Height / 2), .1f, SpriteEffects.None, 0f);
                        shipdraw = true;
                    }
                }
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
    }
}
